<?php

//------------------------
// 商品控制器
//-------------------------
namespace app\admin\controller;

use app\common\controller\AdminBase;
use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsAlbum as GoodsAlbumModel;
use app\common\model\GoodsCate as GoodsCateModel;
use app\common\model\GoodsBrand as GoodsBrandModel;
use app\common\model\GoodsType as GoodsTypeModel;
use app\common\model\TypeAttr as TypeAttrModel;
use app\common\model\GoodsAttr as GoodsAttrModel;
use app\common\model\GoodsSpec as GoodsSpecModel;
use app\common\model\UserRank as UserRankModel;
use app\common\model\UserRankPrice as UserRankPriceModel;
use app\common\model\GoodsTypeAttrView as GoodsTypeAttrViewModel;
use app\common\model\GoodsCateBrandView as GoodsCateBrandViewModel;
use think\Config;
use think\Db;
use think\Image;

class Goods extends AdminBase
{
    protected $GoodsModel;
    protected $GoodsAlbumModel;
    protected $GoodsCateModel;
    protected $GoodsBrandModel;
    protected $GoodsTypeModel;
    protected $TypeAttrModel;
    protected $GoodsAttrModel;
    protected $GoodsSpecModel;
    protected $UserRankModel;
    protected $UserRankPriceModel;
    protected $GoodsTypeAttrViewModel;
    protected $GoodsCateBrandViewModel;

    protected function _initialize()
    {
        parent::_initialize();
        $this->GoodsModel              = new GoodsModel();
        $this->GoodsAlbumModel         = new GoodsAlbumModel();
        $this->GoodsCateModel          = new GoodsCateModel();
        $this->GoodsBrandModel         = new GoodsBrandModel();
        $this->GoodsTypeModel          = new GoodsTypeModel();
        $this->TypeAttrModel           = new TypeAttrModel();
        $this->GoodsAttrModel          = new GoodsAttrModel();
        $this->GoodsSpecModel          = new GoodsSpecModel();
        $this->UserRankModel           = new UserRankModel();
        $this->UserRankPriceModel      = new UserRankPriceModel();
        $this->GoodsTypeAttrViewModel  = new GoodsTypeAttrViewModel();
        $this->GoodsCateBrandViewModel = new GoodsCateBrandViewModel();
    }


    // 列表
    public function index(){
        $goods_name  = $this->request->param('goods_name','','trim');
        $status      = $this->request->param('status',0,'intval');
        $cate_id     = $this->request->param('cate_id',0,'intval');
        $start       = $this->request->param('start','','trim');
        $stop        = $this->request->param('stop','','trim');
        $sort        = $this->request->param('sort','','trim');

        $where = array();
        if ($status) {
            $_status = $status == 2?0:1;
            $where['status'] = array('eq',$_status);
        }

        if ($cate_id) {
            $where['cate_id'] = array('eq',$cate_id);
        }
 
 
        if ($goods_name) {
             $where['goods_name'] = array('like','%'.$goods_name.'%');
        }
        //日期搜索
        if ($start) {
            $_start = strtotime(date('Y-m-d 00:00:00', strtotime($start)));
            $where['create_time'] = array('egt',$_start);
        }
        if ($stop) {
            $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime($stop)));
            $where['create_time'] = array('elt',$_stop);
        }
        if ($start && $stop) {
            $_start = strtotime(date('Y-m-d 00:00:00', strtotime($start)));
            $_stop  = strtotime(date('Y-m-d 23:59:59', strtotime($stop)));
            if ($_start > $_stop) {
                $_stop = $_start + 86400;
            }
            $where['create_time'] = array('between',array($_start,$_stop));
        }

        $cateInfo = $this->GoodsCateModel->getTree();
        $this->assign('cateInfo',$cateInfo);

        $info = $this->GoodsModel->where($where)->order($sort)->
          paginate(10,false,['query' => [
            'goods_name'  =>$goods_name,
            'cate_id'     =>$cate_id,
            'status'      =>$status,
            'start'       =>$start,
            'stop'        =>$stop,
            'sort'        =>$sort,
            ] ]);

        $this->assign('goods_name',$goods_name);
        $this->assign('cate_id',$cate_id);
        $this->assign('status',$status);
        $this->assign('start',$start);
        $this->assign('stop',$stop);
        $this->assign('sort',$sort);
        $this->assign('info',$info);

        return $this->fetch('index');
    }


    /**
     * @desc 上传图片页面
     */
    public function uploadImagePage(){
        $goods_id = $this->request->param('goods_id',0,'intval');
        $this->assign('goods_id',$goods_id);

        return $this->fetch('upload_image_page');
    }

    /**
     * @desc 上传相册图片
     */
    public function uploadAlbum() {
        // $data   = $this->request->param('');
        $id   = $this->request->param('goods_id',0,'intval');
        $path = $this->request->param('path','other','trim');

        if (!$id) {
            $this->error('缺少要上传图片的商品id');
        }

        // 获取表单上传文件
        $file = request()->file('file');

        if( true != $file->validate(Config::get('image_validate')) ){
            $this->error('上传文件不符合要求');
        }

        $open_file = Image::open($file);

        $saveName = get_image_name();

        // 剪裁成600*600的缩略图
        $open_file->thumb(600, 600, Image::THUMB_CENTER);

        //生成当天日期的文件夹
        $date_dir = make_date_dir();

        $save_path = Config::get('image_path') . $path . DS . $date_dir;

        if (!file_exists($save_path)) {
            mkdir($save_path, 0755, true);
        }

        // 将图片存储到指定位置
        $info = $open_file->save($save_path . DS . $saveName);

        if($info){
            // 返回图片地址
            $return_url = '/uploads/goods_album/' . $date_dir . DS . $saveName;

            // 保存图名字到数据库
            $data['image'] = $date_dir . DS . $saveName;
            $data['goods_id'] = $id;

            $res =  $this->GoodsAlbumModel->allowField(true)->save($data);

            $return = array('msg' => '上传成功','url'=>$return_url, 'id'=>$this->GoodsAlbumModel->id,'code' => 1);
        }else{
            // 上传失败获取错误信息
            $return = array('msg' => $file->getError(), 'code' => 0);
        }
        echo json_encode($return);
    }

    /**
     * @desc 删除相册图片
     */
    public function deleteAlbum(){
        $id   = $this->request->param('id',0,'intval');

        if (!$id) {
            $this->error('缺少要删除图片的id');
        }

        $where['id'] = array('eq',$id);

        $image = Db('GoodsAlbum')->where($where)->field('image')->find();

        // 删除文件
        delete_file('goods_album',$image['image']);

        $res = $this->GoodsAlbumModel->where($where)->delete();

        if ($res === false) {
            $this->error($this->GoodsAlbumModel->getError());
        } else{
            $this->success('删除成功');
        }

    }

    /**
     * @desc 上传主图片
     */
    public function uploadImage() {
        $id   = $this->request->param('id',0,'intval');
        $path = $this->request->param('path','other','trim');

        if (!$id) {
            $this->error('缺少要上传图片的商品id');
        }

        // 获取表单上传文件
        $file = request()->file('image');

        if( true != $file->validate(Config::get('image_validate')) ){
            $this->error('上传文件不符合要求');
        }

        // 删除替换前的图片
        $image = Db('Goods')->where('id',$id)->field('goods_image')->find();

        // 删除文件
        delete_file('goods',$image['goods_image']);

        // 处理图片
        $open_file = Image::open($file);

        $saveName = get_image_name();

        // 剪裁成600*600的缩略图
        $open_file->thumb(600, 600, Image::THUMB_CENTER);

        //生成当天日期的文件夹
        $date_dir = make_date_dir();

        $save_path = Config::get('image_path') . $path . DS . $date_dir;

        if (!file_exists($save_path)) {
            mkdir($save_path, 0755, true);
        }

        // 将图片存储到指定位置
        $info = $open_file->save($save_path . DS . $saveName);

        // 插入图片地址到数据库
        if($info){
            // 返回图片地址
            $return_url = '/uploads/goods/' . $date_dir . DS . $saveName;

            // 保存图名字到数据库
            $data['goods_image'] = $date_dir . DS . $saveName;
            $data['id'] = $id;

            $res =  $this->GoodsModel->allowField(true)->save($data,$data['id']);

            $return = array('msg' => '上传成功','url'=>$return_url, 'code' => 1);
        }else{
            // 上传失败获取错误信息
            $return = array('msg' => $file->getError(), 'code' => 0);
        }
        echo json_encode($return);
    }


    // 添加页面
    function add(){
        $cateInfo = $this->GoodsCateModel->getTree();
        $this->assign('cateInfo',$cateInfo);

        return $this->fetch('add');
    }

    /**
     * @desc 添加操作
     */
    public function addProc() {
        $data            = $this->request->param();

        // 数据处理
        $data['create_time'] = time();
        $data['newarrival'] = $this->request->param('newarrival',0,'intval');
        $data['recommend'] = $this->request->param('recommend',0,'intval');
        $data['bargain'] = $this->request->param('bargain',0,'intval');

        // 促销时间
        if ($data['promote_start_time']) {
            $data['promote_start_time'] = strtotime(date('Y-m-d 00:00:00', strtotime($data['promote_start_time'])));
        } else {
            $data['promote_start_time'] = 0;
        }

        if ($data['promote_end_time']) {
            $data['promote_end_time'] = strtotime(date('Y-m-d 23:59:59', strtotime($data['promote_end_time'])));
        } else {
            $data['promote_end_time'] = 0;
        }

        if ($data['promote_start_time'] > $data['promote_end_time']) {
            $this->error('促销开始时间不能大于结束时间');
        }

        $validate_result = $this->validate($data, 'Goods.add');

        if ($validate_result !== true) {
                $this->error($validate_result);
        }

        $res = $this->GoodsModel->allowField(true)->save($data);

        if ($res === false) {
            $this->error($this->GoodsModel->getError());
        } else {
            $this->success('添加成功');
        }
    }

    // 编辑页面
    function edit(){
        $id = $this->request->param('id',0,'intval');
        $data = $this->GoodsModel->get($id);
        $this->assign('data',$data);

        // 相册图片
        $albumInfo = $this->GoodsAlbumModel->where('goods_id',$id)->select()->toArray();;
        $this->assign('albumInfo',$albumInfo);

        // 分类
        $cateInfo = $this->GoodsCateModel->getTree();
        $this->assign('cateInfo',$cateInfo);

        // 分类下品牌
        $brandInfo = $this->GoodsCateBrandViewModel->where('platform_goods_cate.id',$data['cate_id']) ->select()->toArray();
        $this->assign('brandInfo',$brandInfo);

        // 类型
        $typeInfo = $this->GoodsTypeModel->select();
        $this->assign('typeInfo',$typeInfo);

        // 类型属性
        $attrInfo = $this->TypeAttrModel->where('type_id',$data['type_id'])->select()->toArray();
        $this->assign('attrInfo',$attrInfo);

        //商品属性表连类型属性表
        $goodsAttrViewInfo = $this->GoodsTypeAttrViewModel->where('platform_goods_attr.goods_id',$data['id'])->select()->toArray();

        // 找到当前商品的所有属性id
        $attr_id = array(0);
        foreach ($goodsAttrViewInfo as $k => $v){
            $attr_id[] = $v['attr_id'];
        }
        $attr_id = array_unique($attr_id);//去掉重复

       // 取出当前类型下的后添加的新属性
        $otherAttrInfo = $this->TypeAttrModel->where('type_id',$data['type_id'])->where('id','not in',$attr_id)->field('attr_name,is_select,opts,id AS attr_id')->select()->toArray();

        //为属性值，属性价格，商品属性id都添加一个空值
        foreach ($otherAttrInfo as $k => $v) {
            $otherAttrInfo[$k]['attr_value'] = '';        
            $otherAttrInfo[$k]['attr_price'] = '';
            $otherAttrInfo[$k]['goods_attr_id'] = '';
        }

        // 把新的属性和原属性合并起来
        if ($otherAttrInfo) {
            $goodsAttrViewInfo = array_merge($goodsAttrViewInfo, $otherAttrInfo);
            usort($goodsAttrViewInfo, 'attr_id_sort');
        }

        $this->assign('goodsAttrViewInfo',$goodsAttrViewInfo);

        //会员级别
        $userRankInfo = $this->UserRankModel->select()->toArray();
        // 会员级别价格
        $userRankPriceInfo = $this->UserRankPriceModel->where('goods_id',$id)->select()->toArray();

        for ($i=0; $i < count($userRankInfo) ; $i++) { 
            $userRankInfo[$i]['price'] = '';
            for ($j=0; $j < count($userRankPriceInfo); $j++) { 
                if ($userRankInfo[$i]['id'] == $userRankPriceInfo[$j]['user_rank_id']) {
                    $userRankInfo[$i]['price'] = $userRankPriceInfo[$j]['price'];
                }
            }
        }

        $this->assign('userRankInfo',$userRankInfo);

        return $this->fetch('edit');
    }

    // 编辑操作
    function editProc(){
        $data  = $this->request->param('');
        $scene = $this->request->param('scene','','trim');

        $data['update_time'] = time();

        // 修改基础信息需要数据处理
        if ($scene == 'editBasics') {
            $data['newarrival'] = $this->request->param('newarrival',0,'intval');
            $data['recommend'] = $this->request->param('recommend',0,'intval');
            $data['bargain'] = $this->request->param('bargain',0,'intval');

            if ($data['promote_start_time']) {
            $data['promote_start_time'] = strtotime(date('Y-m-d 00:00:00', strtotime($data['promote_start_time'])));
            } else {
                $data['promote_start_time'] = 0;
            }

            if ($data['promote_end_time']) {
                $data['promote_end_time'] = strtotime(date('Y-m-d 23:59:59', strtotime($data['promote_end_time'])));
            } else {
                $data['promote_end_time'] = 0;
            }

            if ($data['promote_start_time'] > $data['promote_end_time']) {
                $this->error('促销开始时间不能大于结束时间');
            }
        }

        // 如果修改属性和类型则转到GoodsAttr控制器处理
        if ($scene == 'editGoodsAttr') {
            action('admin/GoodsAttr/editProc');
        }

        // 如果修改会员价格则转到UserRank控制器处理
        if ($scene == 'editUserPrice') {
            action('admin/UserRank/editPrice');
        }


        //根据传入的scene生成不同的场景
        $validate_result = $this->validate($data, 'Goods.'.$scene);

        if ($validate_result !== true) {
                $this->error($validate_result);
        }

        // allowField表示过滤非数据表中字段的数据
        $res = $this->GoodsModel->allowField(true)->save($data,$data['id']);

        if ($res === false) {
            $this->error($this->GoodsModel->getError());
        } else {
            $this->success('保存成功');
        }
    }



    // 删除操作
    public function delete(){
        $id = $this->request->param('id',0,'intval');

        // 找出对应商品相片相册所有图片的id集合
        $albumIds = $this->GoodsAlbumModel->field('id')->where('goods_id',$id)->select()->toArray();

        // 先找出商品的主图片路径
        $image = Db('Goods')->where('id',$id)->field('goods_image')->find();

        $where['id'] = array('eq',$id);

        $res = $this->GoodsModel->where($where)->delete();

        if ($res === false) {
            $this->error($this->GoodsModel->getError());
        } else{
            // 删除商品主图片
            delete_file('goods',$image['goods_image']);

            // 循环删掉对应的相册图片
            for ($i=0; $i < count($albumIds) ; $i++) {
                $album_id = 0;
                $album_id =  $albumIds[$i]['id'];

                $album_image = Db('GoodsAlbum')->where('id',$album_id)->field('image')->find();

                // 删除文件
                delete_file('goods_album',$album_image['image']);
            }

            // 最后删掉相册图片的数据
            $this->GoodsAlbumModel->where('goods_id',$id)->delete();

            // 删除商品相关属性
            $this->GoodsAttrModel->where('goods_id',$id)->delete();

            $this->success('删除成功');
        }
    }


    // 批量处理
    public function batchProc(){
        $data = $this->request->param();

        $ids = implode(',',$data['ids']);
        $map['id']  = ['in',$ids];
        $type = $data['type'];

        switch ($type) {
            case 'disable':
                $res = $this->GoodsModel->where($map)->update(['status' => '0']);
                $act = '下架';
                break;
            case 'enable':
                $res = $this->GoodsModel->where($map)->update(['status' => '1']);
                $act = '上架';
                break;

            default:
                $this->error('非法操作');
                break;
        }

        if ($res === false) {
            $this->error($this->GoodsModel->getError());
        } else {
            $this->success('批量'.$act.'成功');
        }

    }

    // 设置商品规格页面
    public function setGoodsSpec(){
        $id = $this->request->param('id',0,'intval');
        $this->assign('goods_id',$id);

        // 商品类型
        $type = $this->GoodsModel->where('id',$id)->field('type_id')->find()->toArray();
        $type_name = $this->GoodsTypeModel->where('id',$type['type_id'])->find();
        $this->assign('type_name',$type_name['type_name']);

        $specInfo = Db('TypeSpec')->where('type_id',$type['type_id'])->select()->toArray();
        for ($i=0; $i < count($specInfo); $i++) { 
            $specInfo[$i]['item'] = Db('SpecItem')->where('spec_id',$specInfo[$i]['id'])->select()->toArray();
        }
        // 规格选项
        $this->assign('specInfo',$specInfo);


        $specItemInfo = $this->GoodsSpecModel->where('goods_id',$id)->select()->toArray();
        // 转换成json字符串
        $specItemInfoJson = json_encode($specItemInfo);
        // 当前商品已设置规格值
        $this->assign('specItemInfoJson',$specItemInfoJson);


        // 合并
        $specIdArray = array();
        foreach ($specItemInfo as $k => $v) {
            $specIdArray = array_merge($specIdArray,explode('_',$v['key']));
        }
        // 去重
        $specIdArray = array_unique($specIdArray);
        // 当前商品已选择规格项目
        $this->assign('specIdArray',$specIdArray);


        return $this->fetch('set_goods_spec');
    }

    // 设置商品规格操作
    public function setGoodsSpecProc(){
        $goods_id = $this->request->param('goods_id',0,'intval');
        $data     = $this->request->param('');

        $addData = array();
        $i = 0;
        foreach ($data['price'] as $k => $v) {

            $key_name = '';
            $k_array = explode('_',$k); 

            foreach ($k_array as $k1 => $v1) {
                $spen_item = Db('SpecItem')
                ->join('platform_type_spec','platform_spec_item.spec_id = platform_type_spec.id')
                ->field('platform_spec_item.item,platform_type_spec.spec_name')
                ->where('platform_spec_item.id',$v1)
                ->find();

                $key_name .= $spen_item['spec_name'].':'.$spen_item['item']." ";
            }

            $addData[$i]['goods_id']    = $goods_id;
            $addData[$i]['key']         = $k;
            $addData[$i]['key_name']    = trim($key_name);
            $addData[$i]['price']       = $v;
            $addData[$i]['store_count'] = $data['store_count'][$k];
            $addData[$i]['sku']         = $data['sku'][$k];

            $validate_result = $this->validate($addData[$i], 'GoodsSpec');

            if ($validate_result !== true) {
                    $this->error($validate_result);
            }

            $i = ++$i;
        }

        // 先将设置商品下的所有规格价钱与库存等数据删除
        $this->GoodsSpecModel->where('goods_id',$goods_id)->delete();

        // 批量添加
        $res = $this->GoodsSpecModel->saveAll($addData);

        if ($res === false) {
            $this->error($this->GoodsSpecModel->getError());
        } else {
            $this->success('保存成功');
        }

    }




}